import asyncio
import websockets as ws
from websockets import ConnectionClosed

count = 0


async def hello():
    uri = "ws://localhost:8899"

    while True:
        try:
            async with ws.connect(uri) as websocket:
                await websocket.send("start")
                while True:
                    try:
                        recv = await websocket.recv()
                        print("recv: ", recv)
                        await asyncio.sleep(5)
                        await websocket.close()
                    except ConnectionClosed as e:
                        print(e.code)
                        if e.code == 1006:
                            print("restart")
                            await asyncio.sleep(2)
                            break
                        elif e.code == 1000:
                            print("客户端主动close")
                            return
                        else:
                            print("other")
                            return
        except ConnectionRefusedError as e:
            print(e)
            global count
            if count == 10:
                return
            count += 1
            await asyncio.sleep(2)


asyncio.get_event_loop().run_until_complete(hello())
